package com.hoyo.service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Set;

import javax.security.auth.login.AccountNotFoundException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.hoyo.common.AppConstant;
import com.hoyo.common.VerifyCode;
import com.hoyo.config.MainFinalConfig;
import com.hoyo.domain.Catalog;
import com.hoyo.domain.ModuleInfo;
import com.hoyo.domain.User;
import com.hoyo.domain.UserInfo;
import com.hoyo.mapper.UserMapper;
import com.hoyo.utils.CommonUtils;
import com.hoyo.utils.MailUtils;
import com.hoyo.utils.MessageUtils;

@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ModuleService moduleService;
	
	private Logger logger = Logger.getLogger(UserServiceImpl.class);
	/**
	 * 根据账号Account查询当前用户
	 * @param account
	 * @return
	 */
	public User findByIdentifier(String identifier)  throws Exception{
		return userMapper.findByIdentifier(identifier);
	}

	/**
	 * 获取资源集合
	 * @param account
	 * @return
	 */
	public Set<String> findPermissions(String identifier)  throws Exception{
		Set<String> set = Sets.newHashSet();
		User user = findByIdentifier(identifier);
		List<ModuleInfo>modules = moduleService.findModuleByUserId(user.getId());
		
		for(ModuleInfo info: modules) {
			set.add(info.getModuleKey());
		}
		return set;
	}

	/**
	 * 获取URL权限
	 * @param account
	 * @return
	 */
	public List<String> findPermissionUrl(String dentify)  throws Exception{
		List<String> list = Lists.newArrayList();
		User user = findByIdentifier(dentify);
		List<ModuleInfo>modules = moduleService.findModuleByUserId(user.getId());
		
		for(ModuleInfo info: modules) {
			if(info.getModuleType() == ModuleInfo.URL_TYPE) {
				list.add(info.getModulePath());
			}
		}
		return list;
	}
	
	@Override
	@Transactional
	public void register(UserInfo info) throws Exception {
//		1.将注册信息转换为用户、信息实体
		User user = new User();
		BeanUtils.copyProperties(user, info);
		user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
		user.setIsLocked(false);
		userMapper.saveUser(user);
		UserInfo userInfo = new UserInfo();
		BeanUtils.copyProperties(userInfo, info);
		if("".equals(userInfo.getNickname())){
			userInfo.setNickname(CommonUtils.generateRandomName());
		}
		userInfo.setUserId(user.getId());
		userInfo.setExp(300);
		userInfo.setIcon("/hoyo/img/morentouxiang.jpg");
		userMapper.saveUserInfo(userInfo);
//		2.用户对象关联角色
		userMapper.relateRole(user.getId(), MainFinalConfig.USER_NORMAL);
	}

	@Override
	@Transactional
	public void modifyPassword(String identifier, String password) throws Exception {
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 ‘"+username+"’ 不存在");
		}
		userMapper.modifyPasswordByUserId(new Md5Hash(password, MainFinalConfig.SALT).toHex(), user.getId());
	}
	
	@Override
	@Transactional(readOnly=true)
	public boolean emailRepeatCheck(String email) throws Exception {
		User user = userMapper.findUserByEmail(email);
		logger.info("is customer always not null? "+ user==null);
		if(user != null){
			return true;
		}
		
		return false;
	}

	@Override
	@Transactional(readOnly=true)
	public boolean telephoneRepeatCheck(String telephone) throws Exception {
		User user = userMapper.findUserByTelephone(telephone);
		if(user != null){
			return true;
		}
		return false;
	}
	
	@Override
	@Transactional
	public void bindTelephone(String identifier, String telephone)  throws Exception{
		
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+username+"' 不存在");
		}
		userMapper.modifyTelephoneByUserId(telephone, user.getId());
	}
	

	@Override
	@Transactional(readOnly=true)
	public void unbindTelephone(String identifier) throws Exception {
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+username+"' 不存在");
		}
		userMapper.modifyTelephoneByUserId(null, user.getId());
	}

	@Override
	@Transactional
	public void modifyNickname(String identifier, String account)  throws Exception{
		
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+ username+ "' 不存在!");
		}
		userMapper.modifyAccountByUserId(account, user.getId());;
	}

	@Override
	@Transactional
	public void modifyIconInfo(String identifier, String iconUrl) throws Exception {
		
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+ username+ "' 不存在!");
		}
		userMapper.modifyIconByUserId(iconUrl, user.getId());
	}
	
	@Override
	@Transactional
	public void bindEmail(String identifier, String email)  throws Exception{

		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+username+"' 不存在");
		}
		userMapper.modifyEmailByUserId(email, user.getId());
	}
	
	@Override
	@Transactional(readOnly=true)
	public void unbindEmail(String identifier) throws Exception {
		
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+username+"' 不存在");
		}
		userMapper.modifyEmailByUserId(null, user.getId());
	}

	@Override
	public VerifyCode sendEmailCode(String identifier) throws Exception {
//		1.通过用户名获取用户对象
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+ username+ "' 不存在!");
		}
//		2.给顾客的旧电子邮箱下发验证码，验证身份
//		2.1 生成验证码信息
		String verifyCode = CommonUtils.generateVerifyCode();
//		2.2 发送信息
		MailUtils.send("hoyo", String.format(AppConstant.MESSAGE_CODE_TEMPLATE, verifyCode), user.getEmail());
//		3.返回验证码信息
		
		return new VerifyCode(verifyCode, System.currentTimeMillis(), 60*5*1000, true);
	}

	@Override
	public VerifyCode sendTelephoneCode(String identifier) throws Exception {
		
		User user = userMapper.findByIdentifier(identifier);
		if(user == null){
//			throw new UsernameNotFoundException("用户名 '"+ username+ "' 不存在!");
		}
		String telephone = user.getPhone();
		String code = CommonUtils.generateVerifyCode();
		String params = "{\"code\":\""+code+"\",\"product\":\"hoyo\"}";
		boolean success = MessageUtils.send(telephone,AppConstant.Message.TEMPLATE_CODE, params);
		if(success){
			return new VerifyCode(code, System.currentTimeMillis(), 5*60*1000, true);
		}else{
			return null;
		}
	}

	@Override
	public UserInfo lookup(String username) throws Exception {
		
		
		
		return null;
	}
	
	@Override
	public UserInfo findUserInfoByUserId(int userId) {
		// TODO Auto-generated method stub
		UserInfo userInfo = userMapper.findUserInfoByUserId(userId);
		return userInfo;
	}

	@Override
	public void updatePersonInfo(UserInfo userInfo) throws Exception {
		// TODO Auto-generated method stub
		userMapper.updatePersonInfo(userInfo);
	}
}
